package com.example.coursedesign.ui.home.dao;


import com.example.coursedesign.ui.home.entity.mRemind;
import com.example.coursedesign.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class mRemindDao {

    private static final String TAG = "mysql-coursedesign-mRemindDao";

    // 日志工具（可以根据需要替换成其他日志框架）
    private static final Logger logger = Logger.getLogger(mRemindDao.class.getName());

    public mRemind create(mRemind remind) throws SQLException {
        String sql = "INSERT INTO mremind (name, picture, number, time, currentNumber, remindTime, detail, status, account) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = JDBCUtils.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {

            if (conn == null || pstmt == null) {
                throw new SQLException("Database connection or PreparedStatement creation failed");
            }

            pstmt.setString(1, remind.getName());
            pstmt.setString(2, remind.getPicture());
            pstmt.setString(3, remind.getNumber());
            pstmt.setString(4, remind.getTime());
            pstmt.setString(5, remind.getCurrentNumber());
            pstmt.setString(6, remind.getRemindTime());
            pstmt.setString(7, remind.getDetail());
            pstmt.setString(8, remind.getStatus());
            pstmt.setString(9, "user123"); // 使用传入的账户名代替硬编码

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        remind.setId(rs.getInt(1));
                    }
                }
            } else {
                logger.warning("No rows were inserted for the provided mRemind object.");
            }
        } catch (SQLException e) {
            logger.severe("Exception during create operation: " + e.getMessage());
            throw e;
        }
        return remind;
    }

    public List<mRemind> findAll() throws SQLException {
        List<mRemind> reminds = new ArrayList<>();
        String sql = "SELECT * FROM mremind";

        try (Connection conn = JDBCUtils.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                reminds.add(new mRemind(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("picture"),
                        rs.getString("number"),
                        rs.getString("time"),
                        rs.getString("currentNumber"),
                        rs.getString("remindTime"),
                        rs.getString("detail"),
                        rs.getString("status"),
                        rs.getString("account")
                ));
            }
        } catch (SQLException e) {
            logger.severe("Exception during findAll operation: " + e.getMessage());
            throw e;
        }
        return reminds;
    }

    public mRemind findById(Integer id) throws SQLException {
        String sql = "SELECT * FROM mremind WHERE id = ?";
        mRemind remind = null;

        try (Connection conn = JDBCUtils.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    remind = new mRemind(
                            rs.getInt("id"),
                            rs.getString("name"),
                            rs.getString("picture"),
                            rs.getString("number"),
                            rs.getString("time"),
                            rs.getString("currentNumber"),
                            rs.getString("remindTime"),
                            rs.getString("detail"),
                            rs.getString("status"),
                            rs.getString("account")
                    );
                }
            }
        } catch (SQLException e) {
            logger.severe("Exception during findById operation: " + e.getMessage());
            throw e;
        }
        return remind;
    }

    public boolean update(mRemind remind) throws SQLException {
        String sql = "UPDATE mremind SET name = ?, picture = ?, number = ?, time = ?, currentNumber = ?, remindTime = ?, detail = ?, status = ? WHERE id = ?";
        int affectedRows = 0;

        try (Connection conn = JDBCUtils.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, remind.getName());
            pstmt.setString(2, remind.getPicture());
            pstmt.setString(3, remind.getNumber());
            pstmt.setString(4, remind.getTime());
            pstmt.setString(5, remind.getCurrentNumber());
            pstmt.setString(6, remind.getRemindTime());
            pstmt.setString(7, remind.getDetail());
            pstmt.setString(8, remind.getStatus()); // status should be set before id
            pstmt.setInt(9, remind.getId()); // id should be the last parameter

            affectedRows = pstmt.executeUpdate();
        } catch (SQLException e) {
            logger.severe("Exception during update operation: " + e.getMessage());
            throw e;
        }
        return affectedRows > 0;
    }

    public boolean delete(Integer id) throws SQLException {
        String sql = "DELETE FROM mremind WHERE id = ?";
        int affectedRows = 0;

        try (Connection conn = JDBCUtils.getConn();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);
            affectedRows = pstmt.executeUpdate();
        } catch (SQLException e) {
            logger.severe("Exception during delete operation: " + e.getMessage());
            throw e;
        }
        return affectedRows > 0;
    }
}